package egovframework.npqs.pqi.mobile.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsonparser.BuKipThread;
import egovframework.npqs.pqi.mobile.jsonparser.BuKipThread.BuKipThreadCallback;

//부기사항
public class BuKipActivity extends Activity implements BuKipThreadCallback{
	private TextView titleTxt, navigation;	// 상단 타이틀
	private AppStatus myapp;
	private String remCd;
	private Context context;
	private ListView listView;
	private BuKipAdapter bukipAdapter;
	private BuKipThread bukipThread;
	private EditText edit_prod_name;
	private ImageButton search_btn, btnHome, btn_exit;
	private Intent intent;
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("부기사항조회");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_bukip);
		
		Intent intent = getIntent();
		remCd = intent.getStringExtra("remCd");
		
		init();
		
	}
	
	private void init(){
		context = this;
		myapp = (AppStatus) context.getApplicationContext();
		myapp.startBroker(context);
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("부기사항조회");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		listView = (ListView)findViewById(R.id.bukip_list);
		bukipAdapter = new BuKipAdapter();
		
		edit_prod_name = (EditText)findViewById(R.id.edit_prod_name);
		
		search_btn=(ImageButton)findViewById(R.id.search_btn);
		search_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				remCd = edit_prod_name.getText().toString();
				myapp.utilm.InputKeybordHidden(context, edit_prod_name);
				searchResult();
			}
		});
		
		btn_exit = (ImageButton)findViewById(R.id.btn_exit);
		btn_exit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		dateLoad();
	}
	
	private void searchResult(){
		
		if(edit_prod_name.getText().toString().equals("")){
			myapp.utilm.ShowDialog(BuKipActivity.this, "실패", "조회할 대상을 입력하세요.", 20);
		}else{
			dateLoad();
		}
	}
	
	private void dateLoad(){
		myapp.showDialogNo(context);	// 페이지가 로드 될때 다이얼로그 출력.
		temp = "조건검색";
		threadStart();
	}
	
	public void threadStart(){
		if("조건검색".equals(temp)){
    		bukipThread = new BuKipThread(context, this, remCd, AppStatus.getmUserId());
    		bukipThread.start();
    	}
	}
	
	@Override
	public void OnBuKipCompleted(boolean isNetworkConntected,
			boolean results, String message) {
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(results) {
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
	}

	@Override
	public void OnBuKipError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				
				bukipAdapter.notifyDataSetChanged();
				listView.setAdapter(bukipAdapter);
				
				if(myapp.getArrBuKipItem().size() == 1){
					returnToActivity();
				}else{
					bukipAdapter.notifyDataSetChanged();
					listView.setAdapter(bukipAdapter);	
				}
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				
				bukipAdapter.notifyDataSetChanged();
				listView.setAdapter(bukipAdapter);
				
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(context, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};
	
	private void returnToActivity(){
		intent = new Intent();
		intent.putExtra("bukipCd", myapp.getArrBuKipItem().get(0).getBukipCd());
		intent.putExtra("bukipNm", myapp.getArrBuKipItem().get(0).getBukipNm());
		setResult(1, intent);
		finish();
	}
	
	class BuKipAdapter extends BaseAdapter {
		TextView text_bukipCd, text_bukipSe, text_natNm, text_regDate, text_itmNm, text_bukipNm;

		@Override
		public int getCount() {
			Log.i("getCount", "getCount");
			return myapp.getArrBuKipItem().size();
		}

		@Override
		public Object getItem(int position) {
			Log.i("getItem", "getItem");
			return myapp.getArrBuKipItem().get(position);
		}

		@Override
		public long getItemId(int position) {
			Log.i("getItemId", "getItemId");
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_bukip_item, parent, false);
    		}
			
			text_bukipCd = (TextView)convertView.findViewById(R.id.text_bukipCd);
			text_bukipSe = (TextView)convertView.findViewById(R.id.text_bukipSe);
			text_natNm = (TextView)convertView.findViewById(R.id.text_natNm);
			text_regDate = (TextView)convertView.findViewById(R.id.text_regDate);
			text_itmNm = (TextView)convertView.findViewById(R.id.text_itmNm);
			text_bukipNm = (TextView)convertView.findViewById(R.id.text_bukipNm);
			
			text_bukipCd.setText(myapp.getArrBuKipItem().get(position).getBukipCd());
			text_bukipSe.setText(myapp.getArrBuKipItem().get(position).getBukipSe());
			text_natNm.setText(myapp.getArrBuKipItem().get(position).getNatNm());
			text_regDate.setText(myapp.getArrBuKipItem().get(position).getRegDate());
			text_itmNm.setText(myapp.getArrBuKipItem().get(position).getItmNm());
			text_bukipNm.setText(myapp.getArrBuKipItem().get(position).getBukipNm());
			
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
			intent = new Intent();
			intent.putExtra("bukipCd", myapp.getArrBuKipItem().get(position).getBukipCd());
			intent.putExtra("bukipNm", myapp.getArrBuKipItem().get(position).getBukipNm());
			setResult(1, intent);
			finish();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}
	
	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
}